package com.xiangmo.travel.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiangmo.travel.Dto.LoginDto;
import com.xiangmo.travel.Dto.UserDto;
import com.xiangmo.travel.Dto.UserUpdateDto;
import com.xiangmo.travel.Dvo.OtherUserDvo;
import com.xiangmo.travel.Dvo.TableCollectDvo;
import com.xiangmo.travel.Entity.*;
import com.xiangmo.travel.Service.TeamService;
import com.xiangmo.travel.Service.UserService;
import com.xiangmo.travel.Utils.PasswordUtil;
import com.xiangmo.travel.mapper.AttractionsCommentsMapper;
import com.xiangmo.travel.mapper.CommunityCommentsMapper;
import com.xiangmo.travel.mapper.UserLikeMapper;
import com.xiangmo.travel.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* @author a1304
* @description 针对表【user】的数据库操作Service实现
* @createDate 2023-03-18 11:59:44
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordUtil passwordUtil;
    @Autowired
    private UserLikeMapper userLikeMapper;
    @Autowired
    private TeamService teamService;
    @Autowired
    private AttractionsCommentsMapper attractionsCommentsMapper;
    @Autowired
    private CommunityCommentsMapper communityCommentsMapper;
    //用户登录判断 登录成功返回token
    @Override
    public String userLogin(LoginDto loginDto) {
        String result = null;
        User user = userMapper.selectByUsername(loginDto.getUsername());
        if(user == null){
            return "usernameError";
        }
        boolean status = passwordUtil.checkPassword(loginDto.getPassword(), user.getPassword());
        if(status){
            result = user.getId().toString();
        }
        return result;
    }
    //注册用户
    @Override
    public int register(UserDto userDto) {
        String password = passwordUtil.bcryptPassword(userDto.getPassword());
        User user = User.builder()
                .username(userDto.getUsername())
                .password(password)
                .email(userDto.getEmail())
                .name(userDto.getName())
                .sex(userDto.getSex())
                .age(userDto.getAge())
                .phone(userDto.getPhone())
                .build();
        return userMapper.insert(user);
    }
    //判断是否存在该用户
    @Override
    public User checkUser(String username){
        return userMapper.selectByUsername(username);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public int setUserInfo(UserUpdateDto userUpdateDto) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getId, userUpdateDto.getId());
        User user = new User();
        user.setAge(userUpdateDto.getAge());
        user.setEmail(userUpdateDto.getEmail());
        user.setImage(userUpdateDto.getImage());
        user.setName(userUpdateDto.getName());
        user.setSex(userUpdateDto.getSex());
        user.setSignature(userUpdateDto.getSignature());
        user.setAbout(userUpdateDto.getAbout());
        user.setPhone(userUpdateDto.getPhone());
        user.setUpdateAt(new Date());
        return userMapper.update(user, lambdaQueryWrapper);
    }


    @Override
    public OtherUserDvo getOtherUserInfo(Long userId, Long likesId) {
        User user = userMapper.selectById(userId);
        OtherUserDvo otherUserDvo = new OtherUserDvo();
        otherUserDvo.setName(user.getName());
        otherUserDvo.setAbout(user.getAbout());
        otherUserDvo.setImage(user.getImage());
        otherUserDvo.setSex(user.getSex());
        otherUserDvo.setAge(user.getAge());
        otherUserDvo.setUserLikeNum(this.getNumOtherLike(userId));
        // 0 未点赞  1 点赞过
        if(this.isLikes(userId, likesId) == 1){
            otherUserDvo.setLikeStatus(1);
        }else {
            otherUserDvo.setLikeStatus(0);
        }
        otherUserDvo.setTeamNum(teamService.getTeamCountByUserId(userId));
        return otherUserDvo;
    }

    @Override
    public Long getNumOtherLike(Long userId) {
        LambdaQueryWrapper<UserLike> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserLike::getUserId, userId);
        return userLikeMapper.selectCount(lambdaQueryWrapper);
    }

    @Override
    public int addUserLike(Long userId, Long likesId) {
        UserLike userLike = UserLike.builder()
                .userId(userId)
                .likesId(likesId)
                .build();
        return userLikeMapper.insert(userLike);
    }

    @Override
    public int deleteUserLike(Long userId, Long likesId) {
        LambdaQueryWrapper<UserLike> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserLike::getUserId, userId)
                        .eq(UserLike::getLikesId, likesId);
        return userLikeMapper.delete(lambdaQueryWrapper);
    }


    @Override
    public int isLikes(Long userId, Long likesId) {
        LambdaQueryWrapper<UserLike> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserLike::getUserId, userId)
                .eq(UserLike::getLikesId, likesId);
        return userLikeMapper.selectCount(lambdaQueryWrapper) > 0L ? 1 : 0;
    }

    @Override
    public List<TableCollectDvo> getCreditPoints(Long userId) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 获取六天前的时间
        LocalDateTime sixDaysBefore = now.minusDays(6);
        // 构建查询条件
        QueryWrapper<UserLike> wrapper = new QueryWrapper<>();
        wrapper.select("DATE(created_at) as created_at", "count(*) as count")
                .eq("user_id", userId)
                .between("created_at", sixDaysBefore, now)
                .groupBy("DATE(created_at)")
                .orderByDesc("created_at");
        // 执行查询
        List<Map<String, Object>> result = userLikeMapper.selectMaps(wrapper);
        // 封装结果
        List<TableCollectDvo> vos = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            TableCollectDvo vo = new TableCollectDvo();
            LocalDate currentDate = LocalDate.now().minusDays(i);
            vo.setCreatedAt(currentDate.toString());
            vo.setCount(0L);
            for (Map<String, Object> map : result) {
                LocalDate dateInMap = ((java.sql.Date) map.get("created_at")).toLocalDate();
                if (currentDate.equals(dateInMap)) {
                    vo.setCount((Long) map.get("count"));
                    break;
                }
            }
            vos.add(vo);
        }
        return vos;
    }

    @Override
    public List<TableCollectDvo> getActive(Long userId) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 获取六天前的时间
        LocalDateTime sixDaysBefore = now.minusDays(6);
        // 构建查询条件
        QueryWrapper<CommunityComments> wrapper = new QueryWrapper<>();
        wrapper.select("DATE(created_at) as created_at", "count(*) as count")
                .eq("user_id", userId)
                .between("created_at", sixDaysBefore, now)
                .groupBy("DATE(created_at)")
                .orderByDesc("created_at");
        // 执行查询
        List<Map<String, Object>> result = communityCommentsMapper.selectMaps(wrapper);
        // 封装结果
        List<TableCollectDvo> vos = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            TableCollectDvo vo = new TableCollectDvo();
            LocalDate currentDate = LocalDate.now().minusDays(i);
            vo.setCreatedAt(currentDate.toString());
            vo.setCount(0L);
            for (Map<String, Object> map : result) {
                LocalDate dateInMap = ((java.sql.Date) map.get("created_at")).toLocalDate();
                if (currentDate.equals(dateInMap)) {
                    vo.setCount((Long) map.get("count"));
                    break;
                }
            }
            vos.add(vo);
        }
        return vos;
    }
}
